<?php

namespace app\api\model\scenic;

use think\Db;
use think\Model;


class ScenicEvaluate extends Model
{





    // 表名
    protected $name = 'scenic_evaluate';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public function add($params)
    {
        Db::startTrans();

        try {
            $content = $params['content'];
            $images = $params['images'];
            $scenic_id = $params['scenic_id'];
            $score = $params['score'];
            $user_id = $params['user_id'];
            if (!$scenic_id)throw new \Exception('参数缺少');
            if (empty($content))throw new \Exception('请输入评价内容');
            if ($score < 0.0 || $score > 5.0) {
                throw new \Exception('无效的评分值');
            }

            $info = ScenicEvaluate::get(['user_id'=>$user_id, 'scenic_id'=>$scenic_id]);
            //if ($info)throw new \Exception('已评价');
            $evaluate_model = new ScenicEvaluate;

            $data = [
                'user_id'=>$user_id,
                'scenic_id'=>$scenic_id,
                'content'=>$content,
                'images'=>$images,
                'score'=>$score
            ];

            $res = $evaluate_model->save($data);
            if ($res){
                Scenic::where(['scenic_id'=>$scenic_id])->setInc('comment_num');

                $scenic_info = Scenic::get($scenic_id);
                $count = ScenicEvaluate::where(['scenic_id'=>$scenic_id])->count();
                $num = ScenicEvaluate::where(['scenic_id'=>$scenic_id])->count();
                $last_count = $count + $num;
                //$new_avg = ($scenic_info['score'] * $new_total + $score) / $new_total;

                if ($score > 0) {
                    $avg_desccredit = ($scenic_info["score"] * $count + $data["score"] * $num) / $last_count;

                    $scenic_info->score = $avg_desccredit;
                    $scenic_info->save();
                }

                Db::commit();
                return $res;
            } else {
                Db::rollback();
                throw new \Exception('评价失败');
            }


        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage().'-'.$e->getLine());
        }

    }


}
